package com.ruoyi.security.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.omp.api.RemoteActMaintainOrderService;
import com.ruoyi.omp.api.domain.ActMaintainOrderData;
import com.ruoyi.omp.api.domain.vo.ActMaintainOrderDataVO;
import com.ruoyi.security.domain.InspectionLocation;
import com.ruoyi.security.domain.InspectionRecord;
import com.ruoyi.security.domain.vo.InRecordResult;
import com.ruoyi.security.mapper.InspectionRecordMapper;
import com.ruoyi.security.service.IInspectionLocationService;
import com.ruoyi.security.service.IInspectionRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 巡更记录Service业务层处理
 *
 * @author cjie
 * @date 2022-04-14
 */
@Slf4j
@Service
public class InspectionRecordServiceImpl implements IInspectionRecordService {
    @Autowired
    private InspectionRecordMapper inspectionRecordMapper;
    @Autowired
    private RemoteActMaintainOrderService remoteActMaintainOrderService;

    @Autowired
    private IInspectionLocationService inspectionLocationService;

    /**
     * 查询巡更记录
     *
     * @param id 巡更记录ID
     * @return 巡更记录
     */
    @Override
    public InspectionRecord selectInspectionRecordById(String id) {
        return inspectionRecordMapper.selectInspectionRecordById(id);
    }

    /**
     * 查询巡更记录列表
     *
     * @param inspectionRecord 巡更记录
     * @return 巡更记录
     */
    @Override
    public List<InspectionRecord> selectInspectionRecordList(InspectionRecord inspectionRecord) {
        if (StringUtils.isNotEmpty(inspectionRecord.getQrCode())) {
            inspectionRecord.setParkNum(null);
        }
        return inspectionRecordMapper.selectInspectionRecordList(inspectionRecord);
    }

    /**
     * 新增巡更记录
     *
     * @param inspectionRecord 巡更记录
     * @return 结果
     */
    @Override
    public int insertInspectionRecord(InspectionRecord inspectionRecord) {
        inspectionRecord.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        inspectionRecord.setCreateTime(DateUtils.getNowDate());
        inspectionRecord.setCreateBy(SecurityUtils.getUsername());
        //判断是白班还是晚班
        String nowDate = DateUtil.now();
        String compareWDate = DateUtil.format(new Date(), "yyyy-MM-dd") + " 05:30:00";
        String compareLDate = DateUtil.format(new Date(), "yyyy-MM-dd") + " 17:30:00";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (sdf.parse(nowDate).getTime() >= sdf.parse(compareWDate).getTime() && sdf.parse(nowDate).getTime() <= sdf.parse(compareLDate).getTime()) {
                inspectionRecord.setShift("白班");
            } else {
                inspectionRecord.setShift("晚班");
            }
        } catch (Exception e) {

        }

        //如果数据存在，不插入记录
        if(isExistLastRecord(inspectionRecord)){
            return 1;
        }
        // 插入表单数据
        ActMaintainOrderData orderData = new ActMaintainOrderData();
        orderData.setFormId(inspectionRecord.getFormId());
        R r = remoteActMaintainOrderService.addData(orderData);
        inspectionRecord.setFormData(r.getData().toString());
        return inspectionRecordMapper.insertInspectionRecord(inspectionRecord);
    }

    private boolean isExistLastRecord(InspectionRecord inspectionRecord){
        // 最新一条记录
        InspectionRecord max = inspectionRecordMapper.selectInspectionRecordMax(inspectionRecord.getRecordType());
        //判断是否相等，是返回true;
        if(max != null && max.getQrCode().equals(inspectionRecord.getQrCode()) && max.getInspectionPerson().equals(inspectionRecord.getInspectionPerson()) && max.getRecordType().equals(inspectionRecord.getRecordType())){
            return true;
        }
        return false;

    }

    /**
     * 修改巡更记录
     *
     * @param inspectionRecord 巡更记录
     * @return 结果
     */
    @Override
    public int updateInspectionRecord(InspectionRecord inspectionRecord) {
        inspectionRecord.setUpdateTime(DateUtils.getNowDate());
        inspectionRecord.setUpdateBy(SecurityUtils.getUsername());
        return inspectionRecordMapper.updateInspectionRecord(inspectionRecord);
    }

    /**
     * 批量删除巡更记录
     *
     * @param ids 需要删除的巡更记录ID
     * @return 结果
     */
    @Override
    public int deleteInspectionRecordByIds(String[] ids) {
        return inspectionRecordMapper.deleteInspectionRecordByIds(ids);
    }

    /**
     * 删除巡更记录信息
     *
     * @param id 巡更记录ID
     * @return 结果
     */
    @Override
    public int deleteInspectionRecordById(String id) {
        return inspectionRecordMapper.deleteInspectionRecordById(id);
    }


    //微信新增巡更记录
    @Override
    public int insertWXInspectionRecord(InspectionRecord inspectionRecord) {
        //远程插入表单数据，否则返回失败
        int row = this.insertInspectionRecord(inspectionRecord);
        if (row < 0) {
            throw new CustomException("插入巡逻结果失败");
        }

        // 更新表单数据
        ActMaintainOrderDataVO orderData = new ActMaintainOrderDataVO();
        orderData.setFormId(inspectionRecord.getFormId());
        orderData.setId(inspectionRecord.getFormData());
        orderData.setFormVariables(inspectionRecord.getFormContent());
        //orderData.setRemark(inspectionRecord.getRemark());
        R r = remoteActMaintainOrderService.remoteSaveFormData(orderData);
        if (r.getCode() == Constants.SUCCESS) {
            return 1;
        } else {
            throw new CustomException("保存巡逻内容失败");
        }

    }

    @Override
    public InspectionRecord selectWXInspectionRecordById(String id) {
        InspectionRecord record = this.selectInspectionRecordById(id);
        ActMaintainOrderData orderData = new ActMaintainOrderData();
        orderData.setId(record.getFormData());
        //远程获取数据
        R r = remoteActMaintainOrderService.getData(orderData);
        ActMaintainOrderDataVO orderDataVO = (ActMaintainOrderDataVO) r.getData();
        record.setFormContent(orderDataVO.getFormVariables());
        return record;
    }

    @Override
    public int updateWXInspectionRecord(InspectionRecord inspectionRecord) {
        int row = this.updateInspectionRecord(inspectionRecord);
        //if varilbe not null,远程更新
        if(!inspectionRecord.getFormContent().isEmpty()){
            ActMaintainOrderDataVO orderDataVO = new ActMaintainOrderDataVO();
            orderDataVO.setId(inspectionRecord.getFormData());
            orderDataVO.setFormId(inspectionRecord.getFormId());
            orderDataVO.setFormVariables(inspectionRecord.getFormContent());
            R r = remoteActMaintainOrderService.remoteSaveFormData(orderDataVO);
            if(r.getCode() != Constants.SUCCESS){
                throw new CustomException("更新表单数据失败");
            }
        }
        return row;
    }

    @Override
    public Map<String,InRecordResult> computeCard(InspectionRecord inspectionRecord) {
        log.info("computeCard: " + inspectionRecord.toString());
        inspectionRecord.setRecordType("巡逻");
        Map<String, InRecordResult> resultMap = new LinkedHashMap<>();
        InspectionLocation search = new InspectionLocation();
        search.setParkNum(inspectionRecord.getParkNum());
        search.setType(inspectionRecord.getRecordType());
        List<InspectionLocation> inspectionLocations = inspectionLocationService.selectInspectionLocationList(search);
        for(InspectionLocation location:inspectionLocations){
            InRecordResult result = new InRecordResult();
            result.setInspectTime(inspectionRecord.getInspectionTime());
            result.setState("正常");
            resultMap.put(location.getQrCode(),result);
        }
        List<InspectionRecord> list = this.selectInspectionRecordList(inspectionRecord);
        //分组，组内时间排序
        for(InspectionRecord record:list){
            //is exsit
            if(resultMap.containsKey(record.getQrCode())){
                InRecordResult tmp = resultMap.get(record.getQrCode());
                if(record.getState().equals("异常")){
                    tmp.setErrorCount(tmp.getErrorCount()+1);
                }else {
                    tmp.setCount(tmp.getCount()+1);
                }
                if(tmp.getInspectTime() !=null && record.getInspectionTime().after(tmp.getInspectTime())){
                    tmp.setInspectTime(record.getInspectionTime());
                    tmp.setState(record.getState());
                }
                //resultMap.put(record.getQrCode(),tmp);
            }
        }
        return resultMap;
    }
}
